<template>
  <div class="file-list-container">
    <div class="table-container">
      <div class="table-header">
        <div class="header-left">
          <el-upload 
            :on-success="handleSuccess" 
            class="upload-demo" 
            :show-file-list="false"
            action="/api/minio/uploadFile" 
            multiple
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :limit="5"
            accept=".pdf,.doc,.docx,.txt,.md,.json">
            <el-button type="primary" class="create-btn">
              <el-icon class="upload-icon">
                <Upload />
              </el-icon>
              上传文件
            </el-button>
            <span class="upload-tip">支持上传小于5MB的文件</span>
          </el-upload>
        </div>
        <el-input v-model="search" size="large" placeholder="搜索文件名..." class="search-input" prefix-icon="Search" />
      </div>

      <el-table :data="filterTableData" style="width: 100%" class="water-drop-table" :header-cell-style="{
        background: 'rgba(236, 245, 255, 0.6)',
        color: '#409EFF',
        fontWeight: 'bold'
      }">
        <el-table-column label="日期" align="center" width="180">
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Timer />
              </el-icon>
              <span>{{ formatDate(scope.row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="文件名" prop="name" min-width="220">
          <template #default="scope">
            <div class="table-cell-content file-name-cell">
              <el-icon class="cell-icon">
                <Document />
              </el-icon>
              <span class="file-name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="大小" align="center" width="120">
          <template #default="scope">
            <div class="table-cell-content">
              <span>{{ formatSize(scope.row.size) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="向量状态" align="center" width="142">
          <template #default="scope">
            <el-tag class="water-drop-tag" :type="scope.row.vectorState === 'Successful' ? 'success' :
              scope.row.vectorState === 'Failed' ? 'danger' : 'info'">
              {{ scope.row.vectorState }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" class="create-btn"
                @click="handleVector(scope.$index, scope.row)">
                <el-icon>
                  <Connection />
                </el-icon>
                <span>生成向量</span>
              </el-button>
              <el-button size="small" type="danger" class="create-btn"
                @click="handleDelete(scope.$index, scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="empty-placeholder" v-if="filterTableData.length === 0">
        <el-empty description="暂无文件" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listFile, deleteFileById, vectorFileById } from '../../api/file-api';
import type { UploadProps, UploadUserFile } from 'element-plus'

interface FileVo {
  id: number
  name: string
  size: number
  fileObjectName: string
  url: string
  vectorState: string
  createTime: string
}
const fileList = ref<FileVo[]>([])
// 定义加载数据的函数
const loadData = () => {
  console.log('loadData---')
  listFile().then((response) => {
    response.forEach((item: any) => {
      fileList.value.push({
        id: item.id,
        name: item.name,
        size: item.size,
        fileObjectName: item.fileObjectName,
        url: item.url,
        vectorState: item.vectorState,
        createTime: item.createTime
      })
    })
  })
}
// 使用 onMounted 钩子在组件加载时调用 loadData
onMounted(() => {
  loadData()
})

// 格式化文件大小为 MB
const formatSize = (size: number): string => {
  if (size === 0) return '0 MB';
  return (size / (1024 * 1024)).toFixed(2) + ' MB'; // 转换为 MB，保留两位小数
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (dateArray: number[]): string => {
  if (!dateArray || dateArray.length < 3) return '';
  const [year, month, day] = dateArray;
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD
}

const search = ref('')
const filterTableData = computed(() =>
  fileList.value.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
)

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  fileList.value.push({
    id: response.id,
    name: response.name,
    size: response.size,
    fileObjectName: response.fileObjectName,
    url: response.url,
    vectorState: response.vectorState,
    createTime: response.createTime
  })
}

const beforeUpload = (file: File) => {
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB');
  }
  return isLt5M;
}

const handleExceed = () => {
  ElMessage.error('一次最多可上传5个文件');
}

const handleVector = (index: number, row: FileVo) => {
  vectorFileById(row.id).then(() => {
    const file = fileList.value.find(item => item.id === row.id);
    if (file) {
      file.vectorState = 'Successful';
    }
    ElMessage.success('vector successfully')
  }).catch(() => {
    const file = fileList.value.find(item => item.id === row.id);
    if (file) {
      file.vectorState = 'Failed';
    }
    ElMessage.error('vector failed')
  })
}
const handleDelete = (index: number, row: FileVo) => {
  deleteFileById(row.id).then(() => {
    fileList.value.splice(index, 1)
  }).catch(() => {
    ElMessage.error('Delete failed')
  })
}

</script>

<style scoped>
.file-list-container {
  padding: 20px;
  margin: 0 auto;
  /* 居中显示 */
}

.table-container {
  background-color: #f9f9fb;
  border-radius: 10px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
  /* 加深阴影效果 */
  border: 1px solid rgba(216, 218, 219, 0.15);
  /* 添加淡蓝色边框 */
  padding: 20px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  /* 添加过渡效果 */
}


.table-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(245, 247, 250, 0.6) 100%);
  border-radius: 8px;
  /* 与容器一致的圆角 */
  z-index: -1;
}

.header-left {
  display: flex;
  align-items: center;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px 15px;
  margin-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  /* 与 chat-sessions 一致的边框 */
}


.create-btn {
  border-radius: 20px;
  &:hover {
    transform: scale(1.05);
  }
}

.upload-icon {
  font-size: 18px;
  margin-right: 4px;
}

.upload-tip {
  margin-left: 16px;
  color: #606266;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 20px;
}

.search-input {
  width: 240px;
  border-radius: 20px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  background: #f9f9fb;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
  /* 添加与 Element Plus 主色调一致的淡蓝色边框 */
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  background: #f0f5fb;
  box-shadow: 0 0 0 1px #409EFF;
  /* 悬停时边框变为更深的蓝色 */
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF, 0 0 0 3px rgba(64, 158, 255, 0.2);
  /* 聚焦时添加外发光效果 */
}

.search-input :deep(.el-input__inner) {
  color: #606266;
}

.water-drop-table {
  margin-top: 16px;
  border-radius: 8px;
  /* 与 chat-sessions 一致的圆角 */
  overflow: hidden;
  background-color: #ffffff;
  /* 与 chat-sessions 中的列表项背景一致 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  /* 与 chat-sessions 中的列表项阴影一致 */
}

.water-drop-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.water-drop-table :deep(.el-table__row:hover) {
  background-color: #f0f7ff !important;
  /* 与 chat-sessions 中的列表项悬停背景一致 */
  transform: translateY(-2px);
  /* 与 chat-sessions 中的列表项悬停效果一致 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.water-drop-table :deep(td.el-table__cell) {
  border-bottom: 1px solid rgba(235, 238, 245, 0.6);
  padding: 12px 15px;
  /* 与 chat-sessions 中的列表项内边距一致 */
}

.table-cell-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cell-icon {
  color: #409EFF;
  font-size: 16px;
  background-color: rgba(236, 245, 255, 0.6);
  padding: 6px;
  border-radius: 8px;
}

.file-name-cell {
  white-space: normal;
  word-break: break-word;
}

.file-name {
  display: inline-block;
}

.water-drop-tag {
  border-radius: 12px;
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
  font-weight: 600;
  box-shadow: 0 2px 6px -2px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.empty-placeholder {
  height: 200px;
  padding: 40px 0;
}
.el-empty{
  padding: 0;
}
</style>